<template lang="">
  <div>
    <van-nav-bar title="商品详情" left-text="返回" left-arrow @click-left="onClickLeft" />

    <van-empty v-if="pid == undefined" image="error" description="商品id不存在-被下架" />

    <div v-else>
      <van-swipe :autoplay="3000" lazy-render>
        <van-swipe-item v-for="(item, index) in images" :key="index">
          <img :src="item" style="width: 100%" />
        </van-swipe-item>
      </van-swipe>
      <h1>{{ productObj.proname }}</h1>
      <h3>{{ productObj.originprice }}</h3>

      <van-action-bar>
        <van-action-bar-icon icon="chat-o" text="客服" dot v-login />
        <van-action-bar-icon
          icon="cart-o"
          text="购物车"
          :badge="cartNum"
          v-login
          to="/layout/cart"
        />
        <van-action-bar-icon icon="shop-o" text="店铺" badge="12" v-login />
        <van-action-bar-button type="warning" text="加入购物车" @click="cartAddClick" v-login />
        <van-action-bar-button type="danger" text="立即购买" v-login />
      </van-action-bar>
    </div>
  </div>
</template>
<script setup lang="ts">
// 获取地址栏的 参数
import { useRoute, useRouter } from 'vue-router'
import { getProducDetail } from '@/api/product'
import { ref } from 'vue'
import { useUser } from '@/stores/user'
import { cartAdd } from '@/api/cart'
import { showFailToast, showToast } from 'vant'
let router = useRouter()
let userStore = useUser()
let cartNum = ref(0)
cartNum.value = userStore.cartNum

// useRoute 当前路由配置信息
let route = useRoute()
let pid = route.query.pid as string //断言 pid的类型

// ref<> 指定ref（参数） 参数的类型
// Array<string>  string 描述的数组参数的类型
let images = ref<Array<string>>([]) //

let productObj = ref({})

if (pid) {
  // 请求商品的详情

  getProducDetail(pid).then((r) => {
    productObj.value = r.data

    for (let i = 1; i < 5; i++) {
      let key = 'img' + i
      let value = r.data[key]
      if (value) {
        images.value.push(value)
      }
    }
  })
} else {
  console.log('商品id不存在-被下架')
}
//

const onClickLeft = () => history.back()

// 加入购物车
function cartAddClick() {
  cartAdd(pid).then((r) => {
    if (r.code == '200') {
      cartNum.value = userStore.cartNum
      showToast({
        message: r.message,
        type: 'success',
        iconSize: '50px'
      })
    } else {
      showFailToast(r.message)
    }
  })
}
</script>
<style lang=""></style>
